﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BySoft.Web.Utility;
using System.Data;
using BySoft.Server.Common.Enum;
using BySoft.Server.Common.Entity;
using BySoft.Server.Business;
using BySoft.Server.Common;
using OneSoft.EntityCore;
using BySoft.Server.Consts;
using BySoft.Server.Common.Schema;

using System.IO;
using System.Configuration;
using BySoft.Web.Controls;

using System.Threading;
using BySoft.Web.Site;


namespace ZCZP.Web.Site.OutSource
{
    /// <summary>
    /// 选取工序，排程中设定为委外＝Y的，且无委外单的
    /// 依工序－排程明细－自动带出物料明细
    /// 可修改出厂物料数量－存档
    /// </summary>
    public partial class OutOrderAdd : AuthBasePage
    {
        int m_count = 0;
        private static int iPageIndex = 0;

        #region 变量定义
      
        protected DataTable BillDetailDT
        {
            get
            {
                if (Session["BillDetailDT"] != null)
                {
                    return (DataTable)Session["BillDetailDT"];
                }
                else
                {
                    return CreateDetailDT();
                }
            }
            set
            {
                Session["BillDetailDT"] = value;
            }
        }

      
        private DataTable CreateDetailDT()
        {
            return BsOutorder.CreateDetailDT();
        }



        #endregion

        #region 初始化及绑定数据

        void InitData()
        {
            lblBillID.Text = ClsComm.GetBillCode("BS_OutOrder", "BillID", "WO" + DateTime.Now.ToString("yyyyMM"), 4);

            cpBillDate.Value = DateTime.Now.ToString("yyyy-MM-dd");

            BindData(0);
            SetControlAttr(new BsOutorderEntity(), tBase);
        }

        private void BindData(int pageIndex)
        {
            string strProcessID = CommonMethod.GetString(hidOutProcessID.Value);
            string strScheduleDetailID = CommonMethod.GetString(hdScheduleDetailID.Value);
            string strMaterialID = txtBackMaterialID.Text.Trim();

            if (string.IsNullOrEmpty(strProcessID))
            {
                return;
            }


            DataTable dtProcessDetail =
                        BsOutorder.SelectOutProcessDetail(strScheduleDetailID, strProcessID);
         
            BillDetailDT = dtProcessDetail.Copy();

            if (dtProcessDetail.Rows.Count > 0)
            {
                //header
                DataRow dr0 = dtProcessDetail.Rows[0];
                txtScheduleID.Text = CommonMethod.GetString(dr0["ScheduleID"]);

                txtWorkOrderNo.Text = CommonMethod.GetString(dr0["WorkOrderNo"]);
                txtBackNums.Text = CommonMethod.GetString(dr0["BackNums"]);
                txtOutProcessName.Text = CommonMethod.GetString(dr0["ProcessName"]);
                txtOutProcessID.Text = CommonMethod.GetString(dr0["ProcessID"]);
                txtBackProcessID.Text = CommonMethod.GetString(dr0["BackProcessID"]);
                hdOutOrderNum.Value = CommonMethod.GetString(dr0["OutOrderNum"]);
                hdBackOrderNum.Value = CommonMethod.GetString(dr0["BackOrderNum"]);
                hdScheduleDetailID.Value = CommonMethod.GetString(dr0["ScheduleDetailID"]);

                //需要从选取的数据中复制到detail栏位名称
                string[] fldList = new string[] { 
                   "MaterialTypeName","MaterialID","MaterialName","Specifications","Unit","Nums"
                };
                DataTable dtDetail = BsOutorder.SelectDetailData("-1");//生个空的detail

                for (int i = 0; i < dtProcessDetail.Rows.Count; i++)
                {
                    DataRow drProcessDetail = dtProcessDetail.Rows[i];

                    DataRow dr = dtDetail.Rows.Add();
                    CopyDataRowProperty(drProcessDetail, dr, fldList);
                    dr["BillID"] = GetString(lblBillID);
                    dr["DetailID"] = (i + 1).ToString();
                    dr["IsNew"] = "1";
                    dr["IsDel"] = "-1";
                }


                BillDetailDT = dtDetail;

                grdResult.DataSource = dtDetail;

                grdResult.DataBind();
                SetControlAttr(new MdCustomerdetailEntity(), grdResult);

            }
            else
            {
                UIHelper.BindEmptyGridView(grdResult, CreateDetailDT());
            }

            hidOutProcessID.Value = strProcessID;

            UIHelper.RunScript(this, "iframeAutoFit();");
        }

        private void CopyDataRowProperty(DataRow drSource, DataRow drTarget, string[] fldList)
        {
            foreach (string name in fldList)
            {
                drTarget[name] = drSource[name];
            }

        }


        /// <summary>
        /// 取出用户实际输入明细数量
        /// </summary>
        void GetChangeData()
        {
            DataTable dtTemp = BillDetailDT.Copy();
            foreach (GridViewRow gvr in grdResult.Rows)
            {
                if (gvr.RowType == DataControlRowType.DataRow)
                {
                    Label lblID = gvr.FindControl("lblMaterialID") as Label;
                    TextBox txtOutNums = gvr.FindControl("txtNums") as TextBox;

                    DataRow[] drs = dtTemp.Select(string.Format("MaterialID='{0}'", lblID.Text));
                    if (drs != null && drs.Length > 0)
                    {
                        drs[0]["Nums"] = CommonMethod.ConvertToDecimal(GetGridViewString(txtOutNums), 2);

                    }
                }
            }
            BillDetailDT = dtTemp.Copy();
        }
        #endregion

        #region 控件事件
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                iPageIndex = 0;
                Session["BillDetailDT"] = null;
                InitData();

            }
            Master.ValidationGroup = "gSubmit";
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Tabs", "iframeAutoFit();", true);
            //  UIHelper.RunScript(this.UpdatePanel1, "Refreashtab();");
        }




        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (!ValidateData())
            {
                return;
            }
            try
            {
                BsOutorderEntity entity = new BsOutorderEntity();
                entity.BillID = lblBillID.Text;
                if (ClsComm.CheckExist("BS_OutOrder", "BillID", entity.BillID, true))
                {

                    UIHelper.AlertMessage(this.UpdatePanel1, "号码已经存在，请重新按一下确定按钮");
                    lblBillID.Text = ClsComm.GetBillCode("BS_OutOrder", "BillID", "WO" + DateTime.Now.ToString("yyyyMM"), 4); ;
                    return;
                }
                entity.BillDate = GetDateTime(cpBillDate);// Convert.ToDateTime(cpBillDate.Value);
                entity.WorkOrderNo = GetString(txtWorkOrderNo);
                entity.ScheduleID = GetString(txtScheduleID);
               entity.SupplierID = GetString(hidSupplierID);


                entity.OutProcessID = GetString(hidOutProcessID);
                entity.BackMaterialID = GetString(txtBackMaterialID);
                entity.BackMaterialName = GetString(txtBackMaterialName);
                entity.BackNums = GetDecimal(txtBackNums);
                entity.ProcessCost = GetDecimal(txtProcessCost);
                entity.IsFinish = "0";

                entity.BackProcessID = GetString(txtBackProcessID);
                entity.OutOrderNum =CommonMethod.ConvertToDecimal(hdOutOrderNum.Value);
                entity.BackOrderNum = CommonMethod.ConvertToDecimal(hdBackOrderNum.Value);
                entity.ScheduleDetailID = CommonMethod.ConvertToDecimal(hdScheduleDetailID.Value);
         

                //entity.Remark = "";
                entity.CreateUserID = CurrentUser.UserID.Trim();
                entity.CreateUserName = CurrentUser.UserName.Trim();
                entity.CreateDate = DateTime.Now;
                entity.Status = "1";


                GetChangeData();

                ChangeIsNewIsDelFlag(BillDetailDT, "1", "-1");
                BsOutorder.SaveOrUpdate(entity, BillDetailDT, true);
                base.LogAction(BaseEnum.ActionType.Add, entity.ScheduleID.ToString(), true, null, new EntityBase[] { entity });
                Session["BillDT"] = null;
                Session["DetailDT"] = null;
                UIHelper.AlertMessageGoToURL(this.Page, Message.SaveSuccess, "../OutOrder/OutOrderList.aspx");
            }
            catch (Exception ex)
            {
                UIHelper.AlertMessage(this.Page, FomatString(ex.Message.ToString()).ToString());
            }
        }

        private void ChangeIsNewIsDelFlag(DataTable dt, string strIsNew, string strIsDel)
        {
            foreach (DataRow dr in dt.Rows)
            {
                dr["IsNew"] = strIsNew;
                dr["IsDel"] = strIsDel;
            }
        }

        #endregion




        #region Grid事件
        /// <summary>
        ///   行事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grdResult_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            // string strCode = e.CommandArgument.ToString();

        }

        protected void grdResult_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            //if (e.Row.RowType == DataControlRowType.DataRow)
            //{

            //    string strPartsID = CommonMethod.GetString((((DataTable)((GridView)sender).DataSource).Rows[e.Row.RowIndex]["MaterialID"]));

            //    if (string.IsNullOrEmpty(strPartsID))
            //    {
            //        return;
            //    }
            //    //TextBox txtOutNums = (TextBox)e.Row.FindControl("txtNumss");
            //    //Label lblPackNums = e.Row.FindControl("lblPackNums") as Label;
            //    //Label lblOutedNums = e.Row.FindControl("lblOutedNums") as Label;
            //   // txtOutNums.Attributes["onchange"] = "funChangeDetailNum(" + txtOutNums.ClientID + "," + lblPackNums.ClientID + "," + lblOutedNums.ClientID + ");return false;";

            //}
        }
        #endregion

        #region 本地函数 ValidateData


        private bool ValidateData()
        {
            string strMention = "";


            if (BsOutorder.CheckExist(lblBillID.Text.Trim()))
             {
                strMention = "委外单号已经存在！<br />";
            }



            decimal sum = CommonMethod.ConvertToDecimal(txtBackNums.Text, 2);

            if (sum <= 0)
            {
                strMention = "回厂数量不可为空！<br />";
            }

            if (string.IsNullOrEmpty(strMention))
            {
                return true;
            }
            else
            {
                UIHelper.AlertMessage(this.Page, strMention);
                return false;
            }
        }


        #endregion

        #region 选取事件处理
        protected void btnSelectSupplier_Click(object sender, EventArgs e)
        {
            txtSupplierName.Text = "";
            if (string.IsNullOrEmpty(hidSupplierID.Value))
            {
                return;
            }
            MdSupplierEntity en = MdSupplier.GetMdSupplierByID(hidSupplierID.Value);

            txtSupplierName.Text = en.SupplierName;
        }


        protected void btnSelectOutProcessID_Click(object sender, EventArgs e)
        {
            //重新查询一次
            BindData(0);

        }
        protected void btnSelectBackMaterial_Click(object sender, EventArgs e)
        {
            try
            {
                if (Session["BOMMaterialDT"] != null)
                {
                    string materID = GetString(txtBackMaterialID);
                    DataTable dt = (DataTable)Session["BOMMaterialDT"];
                    if (dt.Rows.Count > 0)
                    {
                        DataRow dr = dt.Rows[0];

                        txtBackMaterialID.Text = CommonMethod.GetString(dr["MaterialID"]);
                        txtBackMaterialName.Text = CommonMethod.GetString(dr["MaterialName"]);
                    }

                }

                Session["BOMMaterialDT"] = null;

            }
            catch (Exception ex) { UIHelper.AlertMessage(this, ex.Message.Trim()); }
        }
        #endregion


    }
}
